package com.xfs.controller;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.alibaba.excel.EasyExcelFactory;
import com.microsoft.schemas.vml.STExt;
import com.xfs.common.result.ResultCode;
import com.xfs.common.result.ResultJson;
import com.xfs.entity.po.ExcelData;
import com.xfs.entity.po.User;
import com.xfs.entity.vo.UserVO;
import com.xfs.listener.ExcelListener;
import com.xfs.service.UserService;
import com.xfs.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ClientInfoStatus;
import java.util.List;


/**
 * @Author dwj
 * @Date 2022-05-26 19:28
 */
@Controller
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * TODO 删除
     *  根据ID
     *  POST请求
     * @url user/delete
     * @param id
     * @return
     */
    //    @RequestMapping(method = RequestMethod.POST,value = "{id}")
    @PostMapping("delete")
    @ResponseBody
    public Object deleteUserById(@RequestParam("id") int id){
        return userService.deleteByPrimaryKey(id);
    }

    /**
     * TODO 批量删除
     *  根据多个ID
     * @url user/deleteBatch
     */
    @ResponseBody
    @PostMapping("deleteBatch")
    public ResultJson deleteBatch(@RequestParam("ids") String idsStr){
        String[] ids = idsStr.split(",");
        int num = userService.deleteBatch(ids);
        log.info("批量删除成功{}条" + num);
        return new ResultJson(num, ResultCode.SUCCESS);
    }

    /**
     * TODO 新增用户信息
     *  POST请求
     * @url user/addUserAll 新增全部
     * @url user/addUser    新增部分
     * @param user
     * @return
     */
    @PostMapping("addUserAll")
    @ResponseBody
    public int insert(User user) {
        return userService.insert(user);
    }
    @PostMapping("addUser")
    @ResponseBody
    public int insertSelective(User user) {
        return userService.insertSelective(user);
    }

    /**
     * TODO 查询
     *  根据ID
     *  GET请求
     * @url user/id
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ResponseBody
    public User selectByPrimaryKey(@PathVariable("id") int id) {
        return userService.selectByPrimaryKey(id);
    }


    /**
     * TODO 修改
     * @param user
     * @return
     */
    public int updateByPrimaryKeySelective(User user) {
        return userService.updateByPrimaryKeySelective(user);
    }
    public int updateByPrimaryKey(User user) {
        return userService.updateByPrimaryKey(user);
    }

    /**
     * TODO 更改状态    上架
     */
    @PostMapping("updateStatusByIdUp")
    @ResponseBody
    public ResultJson updateStatusByIdUp(@RequestParam("id") final int id){
        int num = userService.updateStatusById((short) 1, id);
        return new ResultJson(num, ResultCode.SUCCESS);
    }
    /**
     * TODO 更改状态    下架
     */
    @PostMapping("updateStatusByIdDown")
    @ResponseBody
    public ResultJson updateStatusByIdDown(@RequestParam("id") final int id){
        int num = userService.updateStatusById((short) 0, id);
        return new ResultJson(num, ResultCode.SUCCESS);
    }



    /**
     * TODO 用户列表
     * @url /user/list
     * @return
     */

/*    @RequestMapping("list")
    @ResponseBody
    返回页面List<User>改String*/
    @GetMapping("list")
    public String selectList(HttpServletRequest request, UserVO userVO) {
        // 封装查询对象结果集
        List<User> users = userService.selectList();
        // 结果集映射到前端<tbody>
        request.setAttribute("users",users);
        // 返回页面路径
        return "user/list";
    }
    /**
     * TODO 用户列表（条件查询）
     * @url user/listCondition
     */
    @GetMapping("listCondition")
    public String listCondition(HttpServletRequest request, UserVO userVO){
        log.info("获得请求的对象值："+userVO);
        // 回显
        request.setAttribute("userVO",userVO);
        // 封装查询对象结果集
        List<User> users = userService.listCodition(userVO);
        // 结果集映射到前端<tbody>
        request.setAttribute("users",users);
        log.info("获得请求的对象值：" + users);

        return "user/list";
    }


    /**
     * TODO 导入数据(导入按钮页面)
     * @url user/addExcelPage
     */
    @GetMapping("addExcelPage")
    public String addExcelPage(){
        return "user/addExcelPage";
    }
    /**
     * TODO 导入数据(导入值操作)
     * 只能用Post请求
     * @url user/addExcel
     */
/*    @PostMapping
    public String addExcel(@RequestParam("file") MultipartFile multipartFile){
        try {
            EasyExcelFactory.read(multipartFile.getInputStream(), ExcelData.class, new ExcelListener()).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }*/
    @PostMapping("addExcel")
    @ResponseBody
    public ResultJson addExcel(@RequestParam("file") MultipartFile multipartFile) throws IOException {

        List<User> users = ExcelUtils.importExcel(multipartFile, User.class);
        log.info("导入成功");

        // 数据库查询集合
        List<String> listDBEmail = userService.selectUserEmail();
        // 去重业务逻辑
        users = this.repeat(listDBEmail, users);
        // 判断去重后是否为空集合
        if(users.size() == 0){
            log.warn("导入的数据添加失败（因为已经存在）");
            return new ResultJson(users, ResultCode.NOT_DATA);
        }

        // 批量添加
        int num = userService.insertBatch(users);
        log.info("数据添加到SQL成功" + num);
        return new ResultJson(users, ResultCode.SUCCESS);
    }

    /**
     * TODO 用户列表导出（条件）
     * user/export
     */
    @GetMapping("export")
    public void listCondition(UserVO userVO, HttpServletResponse response) throws IOException {
        log.info("获得请求对象值："+userVO);
        List<User> users = userService.listCodition(userVO);
        log.info(String.valueOf(users));
        ExcelUtils.exportExcel(users,"用户信息列表","用户信息", User.class, "用户信息文件", response);
    }

    /**
     * TODO 重复去重方法（两个结果集差集）
     *  判断list集合中的数据是否存在，如果存在，就删除元素
     */
    public List<User> repeat(List<String> listDBEmail,List<User> listEmail){
        for(int i = 0; i < listEmail.size(); i++){
            if(listDBEmail.contains(listEmail.get(i).getEmail())){
                listEmail.remove(listEmail.get(i));
                i--;
            }
        }
        return listEmail;
    }
}
